const response = require('./response')
const jwt = require("jsonwebtoken");
const secret = 'tuisa';
const { noTokenPath } = require("./constData")
const sign = (data, usefulTime = '24h') => {
    return jwt.sign(data, secret, { expiresIn: usefulTime });
};
const verify = async (ctx, next) => {
    if (noTokenPath.includes(ctx.path)) {
        return await next();
    }
    let authHeader = ctx.request.header.authorization || ctx.headers.authorization
    if (!authHeader) {
        delete ctx.userId
        return response.error(ctx, { message: '无登陆凭证', status: 401 })
    }
    try {
        let res = jwt.verify(authHeader.split(' ')[1], secret);
        if (res) {

            ctx.userId = res.id; // 假设JWT载荷中有一个'id'字段

            await next()
        } else {
            delete ctx.userId
            return response.error(ctx, { message: '登陆凭证过期', status: 403 })

        }
    } catch (error) {
        console.log(error, 'error')
        delete ctx.userId
        return response.error(ctx, { message: '非法登陆凭证', status: 401 })
    }
};
module.exports = {
    sign,
    verify,
};
